//配置
window.config = {
	picPathBaseUrl: '/uploadFiles/uploadImgs/',
};

/**
 * UIListView控件
 * @author hmx 20161013
 */
(function($) {
	var pluginName = "UIListView",
		defaults = {
			ajaxType: "GET",
			ajaxDataType: "JSON",
		};

	function Plugin($context, options) {
		this.settings = $.extend(true, defaults, options);
		this.$context = $context
		this.empty();
		this.init();
	}

	Plugin.prototype = {
		test: function() {
			alert('it works!')
		},
		empty: function() {
			this.$context.empty();
		},
		init: function() {
			var self = this;
			self.loadData();
		},
		loadData: function() {
			console.log("^^^^^start:loadData");
			var self = this;
			$.ajax({
				url: self.settings.dataUrl,
				cache:false,
				type: self.settings.ajaxType,
				dataType: self.settings.ajaxDataType,
				data: self.settings.queryData,
				success: function(r) {
					self.loadTpl(r);
				},
				error: function(xhr, errorType, error) {
					alert('^^^^^error:loadData:' + JSON.stringify(errorType) + " " + JSON.stringify(error));
					console.log('^^^^^error:loadData:' + JSON.stringify(errorType) + " " + JSON.stringify(error));
				}
			});
		},
		loadTpl: function(data) {
			console.log("^^^^^start:loadTpl");
			//			console.log(data);
			var self = this;
			$.ajax({
				url: self.settings.itemTplUrl,
				cache:false,
				success: function(r) {
					self.createView(data, r);
				},
				error: function(xhr, errorType, error) {
					alert('^^^^^error:loadTpl:' + JSON.stringify(errorType) + " " + JSON.stringify(error));
					console.log('^^^^^error:loadTpl:' + JSON.stringify(errorType) + " " + JSON.stringify(error));
				}
			});
		},
		createView: function(data, tpl) {
			var self = this;
			for(var i in data.data) {
				var node = tpl;
				for(var p in data.data[i]) {
					//					console.log(p + ":" + data.data[i][p]);
					node = node.replace("{{" + p + "}}", data.data[i][p]);
				}
				//				console.log(node);
				//传入数据
				node = node.replace('{{$row}}', JSON.stringify(data.data[i]));
				node = node.replace('{{picPathBaseUrl}}', $.getContextPath() + window.config.picPathBaseUrl);
				node = node.replace(/\{\{([\S]*)\}\}/g, '-');
				self.$context.append(node);
			}
		}
	}

	$.fn[pluginName] = function(options) {
		var instantiate = function() {
			return new Plugin($(this), options);
		}
		$(this).each(instantiate);
	}

})(jQuery);

(function($) {
	$.extend({
		getContextPath: function() {
			var pathName = document.location.pathname;
			var index = pathName.substr(1).indexOf("/");
			var result = pathName.substr(0, index + 1);
			return result
		},
		getUrlParam: function(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
			var r = decodeURI(window.location.search).substr(1).match(reg); //匹配目标参数
			if(r != null) return unescape(r[2]);
			return undefined; //返回参数值
		}
	});
})(jQuery);